﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using QLPKWeb.BussinessDelegate.CommonDelegate;
using QLPKWeb.BussinessDelegate.LoginHistoryDelegate;
using QLPKWeb.BussinessDelegate.PhanQuyen;
using QLPKWeb.Models.FormBean.PhanQuyen;
using DONGACS.Common;
using DONGACS.DTO;
using QLPKWeb.Models.LinQ.PhanQuyen;
using DigitalLogin;

namespace QLPKWeb.Controllers
{
    public class AuthenticationController : Controller
    {
        UsersServiceDelegate UsersServiceDelegate = new UsersServiceDelegate();
        LoginHistoryDelegate LoginHistoryDelegate = new LoginHistoryDelegate();
        AuthenticationServiceDelegate AuthenticationServiceDelegate = new AuthenticationServiceDelegate();
        public ActionResult ViewChuKySo()
        {
            AuthenticationForm from = new AuthenticationForm();
            from.LoginMessage = "";
            from.Password = "";
            from.IsAuthenticationError = false;
            return View("~/Views/Authentication/LoginChuKySo.aspx",from);
        }

        public ActionResult ViewChangePassChuKySo()
        {
            AuthenticationForm from = new AuthenticationForm();
            from.LoginMessage = "";
            from.Password = "";
            from.IsAuthenticationError = false;
            return View("~/Views/Authentication/ChangePassChuKySo.aspx", from);
        }
        public ActionResult LoginChukySo(HttpPostedFileBase UploadControl, string Pass)
        {
            AuthenticationForm from= new AuthenticationForm();
            bool bKT = false;
             DigitalLogin.DigitalLogin  dgLogin = new DigitalLogin.DigitalLogin();
            dgLogin.PrivateKeyFileName = UploadControl.FileName;
            dgLogin.PrivateKeyStream = UploadControl.InputStream;
            dgLogin.PrivateKeyPassword = Pass;
            dgLogin.PublicKeyFolderPath = ConfigurationManager.AppSettings["UserPublicKeyPath"];
            dgLogin.PrivatePathIpad = ConfigurationManager.AppSettings["PrivatePathIpad"];
            dgLogin.LoginIpad = false;
            //dgLogin.LoginIpadID = KeyIpad;
            bKT = dgLogin.Login();
            if (bKT)
            {
                Session["SeriNumber"]=
                from.LoginMessage = "Login thành công" + dgLogin.SerialNumber;
                if (UsersServiceDelegate.CheckIsActiveCKS(UsersServiceDelegate.GetUserBySeriNumber(dgLogin.SerialNumber).ID) == false)
                {
                    from.LoginMessage = "Tài khoản này chưa được cho phép sử dụng, vui lòng liên hệ người quản trị hệ thống";
                }
                if(UsersServiceDelegate.CheckChangeMatKhauCKS(UsersServiceDelegate.GetUserBySeriNumber(dgLogin.SerialNumber).ID)==false)
                {
                    KhoiTaoSessionChuKySo(UsersServiceDelegate.GetUserBySeriNumber(dgLogin.SerialNumber));
                  return RedirectToAction("ViewChangePassChuKySo");
                }
                else
                {
                    if (UsersServiceDelegate.GetUserBySeriNumber(dgLogin.SerialNumber).PassWordOld == EncodePasswordUser.EncodePassword(Pass))
                    {
                        TB_User userLogin = UsersServiceDelegate.GetUserBySeriNumber(dgLogin.SerialNumber);
                        KhoiTaoSessionChuKySo(userLogin);
                        FormsAuthentication.SetAuthCookie(userLogin.UserName, true);

                        //Lưu lại vết đăng nhập
                        LoginHistoryDelegate.SaveLoginHistory();
                        return RedirectToAction("Index", "Home");
                        
                    }
                    else
                    {
                        from.LoginMessage = "Bạn nhập không đúng mật khẩu";
                    }
                }
            }
            else
            {
                from.LoginMessage = "Login thất bại" + dgLogin.MessageReturn;
            }
            return View("~/Views/Authentication/LoginChuKySo.aspx", from);
        }

        public ActionResult ChangPassChukySo(HttpPostedFileBase UploadControl, string PassOld, string PassNew, string PassNewSecond)
        {
            AuthenticationForm from = new AuthenticationForm();
            bool bKT = false;
            DigitalLogin.DigitalLogin dgLogin = new DigitalLogin.DigitalLogin();
            dgLogin.PrivateKeyFileName = UploadControl.FileName;
            dgLogin.PrivateKeyStream = UploadControl.InputStream;
            dgLogin.PrivateKeyPassword = PassOld;
            bKT = dgLogin.DoiMatKhau(PassNew, this.Response);
            if (bKT)
            {
                    from.LoginMessage = "Đổi mật khẩu thành công, mời bạn đăng nhập lại";
                    UsersServiceDelegate.CapNhatPassChuKySoBySeriNumber(Session["USERID"].ToString(), EncodePasswordUser.EncodePassword(PassNew));
                return View("~/Views/Authentication/LoginChuKySo.aspx", from);
            }
            else
            {
                from.LoginMessage = "Đổi mật khẩu thất bại";
            }
            return RedirectToAction("ViewChangePassChuKySo");
        }

        public ActionResult LayKhoaPublicChuKySo(HttpPostedFileBase UploadControl, string Pass)
        {
            AuthenticationForm from = new AuthenticationForm();
            bool bKT = false;
            DigitalLogin.DigitalLogin dgLogin = new DigitalLogin.DigitalLogin();
            dgLogin.PrivateKeyFileName = UploadControl.FileName;
            dgLogin.PrivateKeyStream = UploadControl.InputStream;
            dgLogin.PrivateKeyPassword = Pass;
            bKT = dgLogin.LayKhoaCongKhai(this.Response);
            if (bKT)
            {
                from.LoginMessage = "Lấy khóa thành công";
            }
            else
            {
                from.LoginMessage = "lấy khóa thất bại";
            }
            return RedirectToAction("ViewChangePassChuKySo");
        }
        public ActionResult Login()
        {
            AuthenticationForm form = new AuthenticationForm();
            bool isDemoProject = Convert.ToBoolean(ConfigurationManager.AppSettings["IsDemoProject"]);
            bool IsDemoFlatForm = Convert.ToBoolean(ConfigurationManager.AppSettings["IsDemoFlatForm"]);
            bool KtView = Convert.ToBoolean(ConfigurationManager.AppSettings["IsLoaiDangNhap"]);
            if(KtView==false)
            {
                return View("~/Views/Authentication/Login.aspx", form);
            }
            else
            {
                return RedirectToAction("ViewChuKySo");
            }
            //if(isDemoProject)
            //{
            //    return View("~/Views/Authentication/DemoProjectLogin.aspx", form);
            //}
            //if (IsDemoFlatForm)
            //{
            //    return View("~/Views/Authentication/DemoFlatFormLogin.aspx", form);
            //}

           
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(AuthenticationForm form)
        {
            bool isDemoProject = Convert.ToBoolean(ConfigurationManager.AppSettings["IsDemoProject"]);
            bool IsDemoFlatForm = Convert.ToBoolean(ConfigurationManager.AppSettings["IsDemoFlatForm"]);
            try
            {
                //Lấy username & Password từ ngừoi dùng
                var username = form.UserName;
                var password = EncodePasswordUser.EncodePassword(form.Password);

                //Lấy thông tin user Login theo username và password cung cấp
                UsersDto userLogin = UsersServiceDelegate.GetUsersByUserNamePassword(username, password);
                if (userLogin == null)
                {
                    //Username password không khớp : Tra về form Login

                    KetThucSession();

                    // Login lỗi
                    form.IsAuthenticationError = true;
                    form.LoginMessage = "Thông tin đăng nhập không chính xác.";

                    if (isDemoProject)
                    {
                        return View("~/Views/Authentication/DemoProjectLogin.aspx", form);
                    }
                    if (IsDemoFlatForm)
                    {
                        return View("~/Views/Authentication/DemoFlatFormLogin.aspx", form);
                    }
                    return View("~/Views/Authentication/Login.aspx", form);
                }
                else // username + password hợp lệ
                {
                    if(userLogin.IsActive == false) // Nhưng tài khoản user đang bị khóa
                    {
                        // Login lỗi
                        form.IsAuthenticationError = true;
                        form.LoginMessage = "Tài khoản yêu cầu đang bị khóa.";

                        if (isDemoProject)
                        {
                            return View("~/Views/Authentication/DemoProjectLogin.aspx", form);
                        }
                        if (IsDemoFlatForm)
                        {
                            return View("~/Views/Authentication/DemoFlatFormLogin.aspx", form);
                        }
                        return View("~/Views/Authentication/Login.aspx", form);
                    }
                    else
                    {
                        //Khởi tạo Session Detail
                        KhoiTaoSession(userLogin);
                        FormsAuthentication.SetAuthCookie(userLogin.UserName, true);
                        //var user = FakeDAL.GetUser(userLogin.UserName);
                        //if(user!=null)
                        //{
                        //   // Session["LoggedInUserName"] = userLogin.UserName;
                        //  //  Session["LoggedInUserId"] = userLogin.ID.ToString();
                        //    ChatService.StartUserSession(System.Web.HttpContext.Current, new MangoChat.User
                        //    {
                        //        UserId = Session["USERID"].ToString(),
                        //        Username = Session["USERNAME"].ToString()

                        //    });
                        // }
                        //Lưu lại vết đăng nhập

                        //var dbus = UsersServiceDelegate.GetUsersById(userLogin.ID.ToString());
                        LoginHistoryDelegate.SaveLoginHistory();
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            catch (SqlException)
            {
                KetThucSession();
                form.IsAuthenticationError = true; // Login lỗi
                form.LoginMessage = "Không thể kết nối server.";
                if (isDemoProject)
                {
                    return View("~/Views/Authentication/DemoProjectLogin.aspx", form);
                }
                if (IsDemoFlatForm)
                {
                    return View("~/Views/Authentication/DemoFlatFormLogin.aspx", form);
                }
                return View("~/Views/Authentication/Login.aspx", form);
            }
            catch(Exception)
            {
                KetThucSession();
                form.IsAuthenticationError = true; // Login lỗi
                form.LoginMessage = "Không thể đăng nhập";
                if (isDemoProject)
                {
                    return View("~/Views/Authentication/DemoProjectLogin.aspx", form);
                }
                if (IsDemoFlatForm)
                {
                    return View("~/Views/Authentication/DemoFlatFormLogin.aspx", form);
                }
                return View("~/Views/Authentication/Login.aspx", form);
            }
        }
        public ActionResult Logout()
        {
            try
            {
                //Lưu lại vết nhật ký sử dụng khi Logout
                LoginHistoryDelegate.UpdateLoginHistory(Convert.ToInt32(Session["LoginHistoryId"]));
                //end

                KetThucSession();
                FormsAuthentication.SignOut();
                return RedirectToAction("Login");
            }
            catch(Exception e)
            {
                KetThucSession();
                FormsAuthentication.SignOut();
                return RedirectToAction("Login");
            }
        }
        
        //public ActionResult Logout()
        //{
        //    FormsAuthentication.SignOut();

        //    //Lưu lại vết khi Logout
        //    LoginHistoryDelegate.SaveLoginHistory(false);
        //    //end

        //    SessionDetail.Clear();
        //    return RedirectToAction("Login");
        //}

        private void KhoiTaoSession(UsersDto userLogin)
        {
            Session["USERID"] = userLogin.ID;
            Session["USERNAME"] = userLogin.UserName;
            Session["PASSWORD"] = userLogin.Password;
            Session["LASTNAME"] = userLogin.LastName;
            Session["FIRSTNAME"] = userLogin.FirstName;
            Session["DEPARTMENT"] = userLogin.Department;
            
            Session["JOBTITLE"] = userLogin.JobTitle;
            Session["ISADMIN"] = userLogin.IsAdministrator;
            Session["EMAIL"] = userLogin.Email;
            Session["LAST_LOGIN"] = userLogin.LastLoginDate;
            Session["PermissionList"] = AuthenticationServiceDelegate.GetPermissionListForUser(userLogin.ID);

            //Session phục vụ phần Nhật ký sử dụng
            Session["LoginHistoryId"] = 0; // Id trong table "LoginHistory" : chứa Id nhật ký login, logout của user login
            Session["LoaiDanhSachCongViecCanXuLy"] = 1;
        }

        private void KhoiTaoSessionChuKySo(TB_User userLogin)
        {
            Session["USERID"] = userLogin.ID;
            Session["USERNAME"] = userLogin.UserName;
          
            Session["PASSWORD"] = userLogin.Password;
            Session["LASTNAME"] = userLogin.LastName;
            Session["FIRSTNAME"] = userLogin.FirstName;
            Session["DEPARTMENT"] = userLogin.Department;
            Session["JOBTITLE"] = userLogin.JobTitle;
            Session["ISADMIN"] = userLogin.IsAdministrator;
            Session["EMAIL"] = userLogin.Email;
            Session["LAST_LOGIN"] = userLogin.LastLoginDate;
            Session["PermissionList"] = AuthenticationServiceDelegate.GetPermissionListForUser(userLogin.ID);

            //Session phục vụ phần Nhật ký sử dụng
            Session["LoginHistoryId"] = 0; // Id trong table "LoginHistory" : chứa Id nhật ký login, logout của user login
            Session["LoaiDanhSachCongViecCanXuLy"] = 1;
        }
        public void KetThucSession()
        {
            Session["USERID"] = 0;
            Session["USERNAME"] = null;
            Session["PASSWORD"] = null;
            Session["LASTNAME"] = null;
            Session["FIRSTNAME"] = null;
            Session["DEPARTMENT"] = 0;
            Session["JOBTITLE"] = 0;
            Session["ISADMIN"] = false;
            Session["EMAIL"] = null;
            Session["LAST_LOGIN"] = DateTime.MinValue;
            Session["PermissionList"] = new List<string>();

            Session["LoaiDanhSachCongViecCanXuLy"] = 0;
        }

        public JsonResult GetUserByUserNamePassword(string username, string password)
        {
            UsersDto usersDto = UsersServiceDelegate.GetUsersByUserNamePassword(username, password);

            if(usersDto == null)
            {
                UsersDto dto = new UsersDto();
                dto.ID = 0;
                return this.Json(dto, JsonRequestBehavior.AllowGet);
            }
            return this.Json(usersDto, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EncodePassword(string password)
        {
            return Json(EncodePasswordUser.EncodePassword(password), JsonRequestBehavior.AllowGet);
        }

        //chứng thực user(đúng username, password nhập)
        public JsonResult IsValidatedUser(string username, string password)
        {
            try
            {
                var userDto = this.UsersServiceDelegate.GetUsersByUserNamePassword(username, EncodePasswordUser.EncodePassword(password));

                if (userDto != null)
                return this.Json(userDto, JsonRequestBehavior.AllowGet);
                //return this.Json(isExist, JsonRequestBehavior.AllowGet);
            }
            catch(SqlException)
            {
                return this.Json("Không thể kết nối server.", JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return this.Json(null, JsonRequestBehavior.AllowGet);
            }

            return this.Json(null, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// User không có quyền truy cập trang
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs((HttpVerbs.Get))]
        public ActionResult NoAccessPermission()
        {
            return View("~/Views/Error/NoAccessPermission.aspx");
        }
        

        /// <summary>
        /// File không tồn tại trong hệ thống
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs((HttpVerbs.Get))]
        public ActionResult FileNotExist()
        {
            return View("~/Views/Error/FileNotExist.aspx");
        }

       /// <summary>
       /// genneral error
       /// </summary>
       [AcceptVerbs((HttpVerbs.Get))]
       public ActionResult Error()
       {
           return View("~/Views/Error/Error.aspx");
       }

       /// <summary>
       /// Forbidden error : 
       /// </summary>
       [AcceptVerbs((HttpVerbs.Get))]
       public ActionResult Error403()
       {
           return View("~/Views/Error/Error403.aspx");
       }

       /// <summary>
       /// Not found page Error
       /// </summary>
       /// <returns>ActionResult value.</returns>
       [AcceptVerbs((HttpVerbs.Get))]
       public ActionResult Error404()
       {
           return View("~/Views/Error/Error404.aspx");
       }
    }
}
